package weibo.tools;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/*
 * 验证码
 */
public class Securitycode {
	private static List<Color> COLORS;
	private BufferedImage image = null;
	private String code = null;
	static {
		COLORS = new ArrayList<>();
		COLORS.add(Color.blue);
		COLORS.add(Color.red);
		COLORS.add(Color.green);
		COLORS.add(Color.yellow);
	}

	/*
	 * 创建验证码（图片）
	 * param height, width, size(字符长度)
	 * 
	 * return BufferedImage
	 */
	public BufferedImage CreateImage(int height, int width, int size) {
		this.image = new BufferedImage(width, height, BufferedImage.TYPE_4BYTE_ABGR);

		Graphics2D graphic = image.createGraphics();
		graphic.setBackground(Color.WHITE);
		graphic.clearRect(0, 0, width, height);
		graphic.setFont(new Font("微软雅黑", Font.ITALIC | Font.BOLD, 20)); // 微软雅黑
																		// 斜体 粗体
																		// 20号
		
		String words = "ABCDEF1234567890";
		StringBuilder wb = new StringBuilder();
		code="";

		Random random = new Random();
		for (int i = 1; i <= size; i++) {
			char ch = words.charAt(random.nextInt(words.length()));
			code+=ch;
			graphic.setColor(getColor(random));// 设置字体颜色
			graphic.drawString(ch + "", (width / size) * i - 30, height / 2 + 10);
			wb.append(ch);
		}
		
		
		// 使用格式
		//ImageIO.write(bufferedImage, "jpg", response.getOutputStream());
		return image;
	}
	/*
	 * 获取验证码
	 */
	public String getcode(){
		return code;
	}
	/*
	 * 获取随机颜色
	 */
	private static Color getColor(Random random) {

		return random == null ? null : COLORS.get(random.nextInt(4));
	}

}
